// -----------------------------------------------------------------------
//  <copyright file="UpdateRoleCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 14:36:07</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Identity.Domain.Entities;
using DaprPlus.Identity.Domain.IntegrationEvents;

using DaprPlus.Identity.Application.Identity.Roles.Queries;

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;

namespace DaprPlus.Identity.Application.Identity.Roles.Commands;

[AuthConfig(typeof(Role), ResourceAccessType.RoleLimit, "Update")]
[MapTo(typeof(Role))]
public class UpdateRoleCommand : IRequest<ApiResult>, ICommand
{
    public required RoleInDto[] Dtos { get; set; }
}

public class UpdateRoleCommandHandler(IServiceProvider provider)
    : IRequestHandler<UpdateRoleCommand, ApiResult>
{
    public async Task<ApiResult> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
    {
        var repository = provider.GetRepository<Role>();
        var roleManager = provider.GetRequiredService<RoleManager<Role>>();
        var updatedRoles = new List<RoleInRecord>();

        foreach (var dto in request.Dtos)
        {
            var entity = await repository.FindAsync(dto.Id, cancellationToken);
            if (entity == null)
            {
                return new ApiResult(ApiResultType.Error, $"编号为 {dto.Id} 的角色信息不存在");
            }
            entity = dto.MapTo(entity);
            var result = await roleManager.UpdateAsync(entity);
            if (!result.Succeeded)
            {
                return new ApiResult(ApiResultType.Error, result.Errors.First().Description);
            }

            var spec = new RoleByIdSpec<Role>(entity.Id);
            entity = await repository.GetAsync(spec, cancellationToken);
            if (entity != null)
            {
                updatedRoles.Add(new RoleInRecord(entity.Id, entity.Name, entity.IsLocked));
            }
        }

        var @event = new RoleUpdatedIntegrationEvent([.. updatedRoles]);
        var uow = provider.GetUnitOfWork();
        uow.AddIntegrationEvent(@event);

        return new ApiResult(ApiResultType.Success, $"角色“{updatedRoles.ExpandAndToString(m => m.Name)}”更新成功");
    }
}

